<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  getTradeMark,
  addOrUpdateTradeMark,
  deleteTradeMarkAPI,
} from "@/api/product/trademark/index.ts";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { Plus } from "@element-plus/icons-vue";
import type { Records, TradeMark } from "@/api/product/trademark/type.ts";
import type { UploadProps } from "element-plus";

let currentPage = ref<number>(1);
let pageSize = ref<number>(5);
let total = ref<number>(0);
let tableData = ref<Records>([]);
let dialogFormVisible = ref<boolean>(false);
let trademark = reactive<TradeMark>({ tmName: "", logoUrl: "" });
let title = ref<string>("");
const formRef = ref();
// 表单验证
const rule = {
  tmName: [
    {
      required: true,
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (value.length > 10) {
          callback(new Error("品牌名称过长"));
        } else if (value.length === 0) callback(new Error("品牌名称不能为空"));
        else callback();
      },
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          callback();
        } else callback(new Error("LOGO不能为空"));
      },
    },
  ],
};

const getTradeMarkInfo = async () => {
  const result = await getTradeMark(currentPage.value, pageSize.value);
  if (result.data.code === 200) {
    total.value = result.data.data.total;
    tableData.value = result.data.data.records;
  }
};

const handleSizeChange = () => {
  getTradeMarkInfo();
};

const handleCurrentChange = () => {
  getTradeMarkInfo();
};

onMounted(() => {
  getTradeMarkInfo();
});

const openDialog = (dialogTitle: string, row: TradeMark) => {
  trademark = {
    tmName: row.tmName,
    logoUrl: row?.logoUrl,
    id: row?.id || undefined,
  };
  title.value = dialogTitle;
  // 清除验证痕迹
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
  dialogFormVisible.value = true;
};

const deleteTradeMark = async (index: number) => {
  console.log(index);
  const result = await deleteTradeMarkAPI(index);
  if (result.data.code === 200) {
    ElMessage.success("删除品牌成功");
    await getTradeMarkInfo();
  } else {
    ElMessage.error("删除品牌失败");
  }
};

const confirm = async () => {
  console.log(trademark);
  // 验证
  await formRef.value.validate();

  const result = await addOrUpdateTradeMark(trademark);
  if (result.data.code === 200) {
    ElMessage.success(trademark.id ? "添加品牌成功" : "添加品牌成功");
    await getTradeMarkInfo();
    dialogFormVisible.value = false;
  } else {
    ElMessage.error(trademark.id ? "编辑品牌失败" : "编辑品牌失败");
  }
};

// 文件上传前的函数。用于约束文件
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 文件类型是 jpeg png gif才能上传
  if (
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/png" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 > 6) {
      ElMessage.error("文件大小不能超过6MB");
      return false;
    }
  } else {
    ElMessage.error("文件类型错误！！！");
    return false;
  }
};
/**
 *
 * @param response 上传成功后的响应
 * @param uploadFile 上传的文件信息和响应信息
 */
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademark.logoUrl = response.data;
  // 清除图片验证结果
  formRef.value.clearValidate("logoUrl");
};
</script>

<template>
  <el-card class="box-card">
    <el-button
      type="primary"
      icon="plus"
      @click="openDialog('添加品牌', { tmName: '', logoUrl: '' })"
      >添加品牌</el-button
    >
    <el-table border style="margin: 10px 0" :data="tableData">
      <el-table-column prop="id" label="序号" width="180" align="center" />
      <el-table-column prop="tmName" label="品牌名称" align="center" />
      <el-table-column label="品牌LOGO" align="center">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="图片" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="openDialog('编辑品牌', row)"
          />
          <el-button
            type="danger"
            size="small"
            icon="delete"
            @click="deleteTradeMark($index)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!--    layout: 可以调整子组件（goto total等）位置。->: 将后面的组件顶到右边 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[4, 6, 8, 10]"
      layout="prev, pager, next, jumper, ->, sizes, total,"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="title" width="35%">
      <el-form
        label-width="80px"
        label-position="right"
        :model="trademark"
        ref="formRef"
        :rules="rule"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input :model="trademark.tmName" />
        </el-form-item>
        <el-form-item label="LOGO" prop="logoUrl">
          <!-- action: 请求URL -->
          <el-upload
            class="avatar-uploader"
            action="http://sph-api.atguigu.cn/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
              alt="picture"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
